import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';
import 'package:casdon/modules/me/data/model/user_info_model.dart';
import 'package:casdon/modules/me/domain/usecase/modify_user_info_uscase.dart';
import 'package:casdon/modules/me/domain/usecase/user_info_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class UserInfoNotifier extends Notifier<UserInfoModel> {
  Future<UserInfoModel> fetchData() async {
    final userInfo = await ref.read(userInfoUsecaseProvider).execute();
    state = UserInfoModel.fromApi(userInfo);
    return state;
  }

  @override
  UserInfoModel build() {
    return UserInfoModel.initial();
  }

  void updateNickName(String value) {
    state = state.copyWith(nickName: value);
  }

  void updateSex(String value) {
    state = state.copyWith(sex: value);
  }

  void updateBirthDay(String value) {
    state = state.copyWith(birthday: value);
  }

  void updateUserAvaTars(String value) {
    state = state.copyWith(userAvatars: value);
  }

  Future<bool> uploadUserInfo() async {
    try {
      String? ossId;
      if (state.userAvatars != null &&
          state.userAvatars!.isNotEmpty &&
          state.userAvatars!.contains("http") == false) {
        ossId = await ref
            .read(ossTokenProvider.notifier)
            .uploadFile(state.userAvatars!);
      }
      if (ossId == null || ossId.isEmpty) {
        final _ = await ref
            .read(modifyUserInfoUscaseProvider)
            .execute(
              nickName: state.nickName,
              sex: state.sex,
              birthday: state.birthday,
            );
      } else {
        final _ = await ref
            .read(modifyUserInfoUscaseProvider)
            .execute(
              nickName: state.nickName,
              sex: state.sex,
              birthday: state.birthday,
              avatar: int.parse(ossId),
            );
      }

      return true;
    } on BusinessException catch (e) {
      Log.e("修改个人信息失败", e, StackTrace.current);
      ToastUtil.show(e.msg);
      return false;
    } catch (e) {
      Log.e("修改个人信息失败", e, StackTrace.current);
      ToastUtil.show(e.toString());
      return false;
    }
  }
}

final userInfoNotifierProvider =
    NotifierProvider<UserInfoNotifier, UserInfoModel>(() {
      return UserInfoNotifier();
    });
